package com.xbq.oauth.security;

import com.xbq.oauth.dao.MemberMapper;
import com.xbq.oauth.model.Member;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Service;


/**
 * 获取用户信息
 */
@Service
@Slf4j
public class MyUserDetailService implements UserDetailsService, SocialUserDetailsService {

    @Autowired
    private MemberMapper memberMapper;

    /**
     * step1：根据用户名，查找用户信息
     * step2：SpringSecurity会根据我们构建的用户信息 与 表单登陆时的用户信息比较！！！
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //log.info("【loadUserByUsername】：开始获取用户信息");
        Member member = memberMapper.selectMemberByUsername(username);
        //判断用户状态
        User user = new User(member.getUsername(),member.getPassword(),
                true,true,true,
                true, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
        return user;
    }

    /**
     * 社交登录的获取用户信息方法
     * @param userId
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
        Member member = memberMapper.selectMemberByUsername(userId);
        SocialUser socialUser = new SocialUser(
                userId,member.getPassword(),true,true,true,true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin")
        );

        return socialUser;
    }

}
